package com.xiaobao.campusLostFoundAfter.controller;

import com.github.pagehelper.PageInfo;
import com.xiaobao.campusLostFoundAfter.common.Result;
import com.xiaobao.campusLostFoundAfter.pojo.User;
import com.xiaobao.campusLostFoundAfter.service.AvatarService;
import com.xiaobao.campusLostFoundAfter.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//用户控制器
@RestController
@RequestMapping("/user")
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    private final AvatarService avatarService;
    private final UserService userService;

    public UserController(AvatarService avatarService, UserService userService) {
        this.avatarService = avatarService;
        this.userService = userService;
    }

    //添加用户
    @PostMapping("/add")
    public Result<String> addUser(@RequestBody User user) {
        return userService.addUser(user);
    }

    //查询所有用户
    @GetMapping("/getAll")
    public Result<List<User>> getAllUsers() {
        return userService.getAllUsers();
    }

    //查询用户
    @GetMapping("/get/{userId}")
    public Result<User> getUserById(@PathVariable String userId) {
        log.info("查询用户{}", userId);
        return userService.getUserById(userId);
    }

    //查询用户
    @GetMapping("/get")
    public Result<User> getUserByName(@RequestParam String userId) {
        log.info("查询用户{}", userId);
        return userService.getUserById(userId);
    }

    //删除用户
    @DeleteMapping("/delete/{userId}")
    public Result<String> deleteUser(@PathVariable String userId) {
        return userService.deleteUser(userId);
    }

    //更新用户
    @PutMapping("/update")
    public Result<String> updateUser(@RequestBody User user) {
        return userService.updateUser(user);
    }

    // 保存用户跟新资料资料
    @PutMapping("/{userId}")
    public Map<String, Object> updateUserInfo(
            @PathVariable String userId,
            @RequestBody Map<String, Object> userData) {
        log.info("更新用户{}信息", userId);
        log.info("用户数据: {}", userData);
        Map<String, Object> result = new HashMap<>();

        try {
            // 获取用户信息
            Result<User> userById = userService.getUserById(userId);
            User user = userById.getData();
            if (user == null) {
                result.put("code", 1);
                result.put("message", "用户不存在");
                return result;
            }
            // 更新可编辑字段
            if (userData.containsKey("phone")) {
                user.setPhone((String) userData.get("phone"));
            }
            if (userData.containsKey("email")) {
                user.setEmail((String) userData.get("email"));
            }
            // 更新用户信息
            user.setUpdateTime(new Date());
            userService.updateUser(user);
            result.put("code", 0);
            result.put("message", "更新成功");
            result.put("data", user);
        } catch (Exception e) {
            result.put("code", 1);
            result.put("message", "更新失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 上传用户头像
     */
    @PostMapping("/upload/avatar")
    public Result<Map<String, String>> uploadAvatar(
            @RequestParam("file") MultipartFile file,
            @RequestParam("userId") String userId,
            @RequestParam(value = "fileExt", required = false) String fileExt) {

        try {
            // 验证文件是否为空
            if (file.isEmpty()) {
                return Result.error(400, "上传的文件不能为空");
            }

            // 验证用户ID
            if (userId == null || userId.trim().isEmpty()) {
                return Result.error(400, "用户ID不能为空");
            }

            // 如果没有提供文件扩展名，从文件名中提取
            if (fileExt == null || fileExt.trim().isEmpty()) {
                String originalFilename = file.getOriginalFilename();
                if (originalFilename != null) {
                    int lastDotIndex = originalFilename.lastIndexOf('.');
                    if (lastDotIndex > 0) {
                        fileExt = originalFilename.substring(lastDotIndex + 1);
                    }
                }
            }

            // 调用服务层处理上传并获取URL
            String fileUrl = avatarService.saveAvatar(file, userId, fileExt);
            userService.updateAvatarUrl(userId, fileUrl);
            // 输出日志（便于调试）
            log.info("上传成功 - 用户ID: {}", userId);
            log.info("存储路径: {}", fileUrl);

            // 构建返回数据
            Map<String, String> resultData = new HashMap<>();
            resultData.put("url", fileUrl);

            return Result.success(resultData);
        } catch (Exception e) {
            // 记录异常日志
            System.err.println("上传头像失败: " + e.getMessage());
            log.info("上传头像失败: {}", e.getMessage());

            return Result.error(500, "上传头像失败: " + e.getMessage());
        }
    }
    //分页查询所有用户
    @GetMapping("/page")
    public Result<PageInfo<User>> getUserByPage(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        return userService.getAllUsersByPage(pageNum, pageSize);
    }
}
